import React, { useState, useEffect, useRef } from "react";
import { Spin } from "antd";
import "../assets/style/ai.css";

const Typewriter = ({
  text,
  speed = 50,
  onComplete,
  className,
  loading = false,
}) => {
  const [displayText, setDisplayText] = useState("");
  const [currentIndex, setCurrentIndex] = useState(0);
  const containerRef = useRef(null);

  useEffect(() => {
    // 当收到新的文本时，重置状态
    setDisplayText("");
    setCurrentIndex(0);
  }, [text]);

  // 添加自动滚动效果
  useEffect(() => {
    if (containerRef.current) {
      containerRef.current.scrollTop = containerRef.current.scrollHeight;
    }
  }, [displayText]);

  useEffect(() => {
    if (loading) {
      // 显示思考中的动画效果
      const thinkingDots = [".", "..", "..."];
      let dotIndex = 0;

      const thinkingTimer = setInterval(() => {
        setDisplayText(`BOSS正在思考${thinkingDots[dotIndex]}`);
        dotIndex = (dotIndex + 1) % thinkingDots.length;
      }, 500);

      return () => clearInterval(thinkingTimer);
    }

    if (!loading && text && currentIndex < text.length) {
      const timer = setTimeout(() => {
        setDisplayText((prev) => prev + text[currentIndex]);
        setCurrentIndex(currentIndex + 1);
      }, speed);

      return () => clearTimeout(timer);
    } else if (!loading && currentIndex >= text.length && onComplete) {
      onComplete();
    }
  }, [currentIndex, text, speed, onComplete, loading]);

  return (
    <div
      ref={containerRef}
      className={`typewriter-text ${className || ""}`}
      style={{
        maxHeight: "400px",
        overflowY: "auto",
        padding: "20px",
      }}
    >
      {loading ? (
        <div style={{ textAlign: "center", padding: "20px" }}>
          <Spin size="large" />
          <p style={{ marginTop: "10px" }}>BOSS正在思考...</p>
        </div>
      ) : (
        <div style={{ whiteSpace: "pre-wrap", wordBreak: "break-word" }}>
          {displayText}
        </div>
      )}
    </div>
  );
};

export default Typewriter;
